package muhtar.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class FileUtil 
{
	public static String getWorkingDirectory() 
	{
		URL url = FileUtil.class.getResource("/muhtar/application/MuhtarApplication.class");
		File base = new File(url.getFile());
		String path = base.getParentFile().getParentFile().getParentFile().getParentFile().getPath() + "/";
		if (path.startsWith("file:")) {
			path = path.substring(5);
		}
		return path;
	}
	
	public static byte[] getBytesFromFile(File file) throws IOException 
	{
		InputStream is = null;
		byte[] bytes = null;
		try {
			is = new FileInputStream(file);
			long length = file.length();
			bytes = new byte[(int)length];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
				offset += numRead;
			}
			if (offset < bytes.length) {
				throw new IOException("Could not completely read file "+file.getName());
			}
		} finally {
			if (is != null) {
				is.close();
			}
		}
		return bytes;
	}

	public static void putBytesToFile(File file, byte[] buffer) throws IOException
	{
		FileOutputStream fs = null;
		
		try {
			fs = new FileOutputStream(file);
			fs.write(buffer);
		} finally {
			if (fs != null) {
				fs.close();
			}
		}
	}
}
